package cn.lzb.book.server.component;

import cn.lzb.book.server.component.convert.CategoryConvert;
import cn.lzb.book.server.dao.po.CategoryPo;
import cn.lzb.book.server.entity.vo.CategoryVo;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liuzhibo
 * @date 2024/8/28 20:53
 **/
public class CategoryHelper {


    public static List<CategoryVo> categoryPo2Tree(List<CategoryPo> categoryPos, CategoryPo rootCategory) {
        if (CollectionUtils.isEmpty(categoryPos)) {
            return Collections.emptyList();
        }

        // 根据code分组
        Map<String, List<CategoryPo>> categoryParentCodeGroup = categoryPos.stream()
                .collect(Collectors.groupingBy(CategoryPo::getParentCode));

        return buildTree(Lists.newArrayList(rootCategory), categoryParentCodeGroup);
    }


    public static List<CategoryVo> categoryPo2Tree(List<CategoryPo> categoryPos) {
        if (CollectionUtils.isEmpty(categoryPos)) {
            return Collections.emptyList();
        }
        // 所有根节点
        List<CategoryPo> rootCategory = categoryPos.stream()
                .filter(elm -> StringUtils.isEmpty(elm.getParentCode()))
                .collect(Collectors.toList());

        // 根据code分组
        Map<String, List<CategoryPo>> categoryParentCodeGroup = categoryPos.stream()
                .collect(Collectors.groupingBy(CategoryPo::getParentCode));

        return buildTree(rootCategory, categoryParentCodeGroup);
    }

    private static List<CategoryVo> buildTree(List<CategoryPo> rootCategory, Map<String, List<CategoryPo>> categoryParentCodeGroup) {
        List<CategoryVo> tree = new ArrayList<>();
        for (CategoryPo root : rootCategory) {
            CategoryVo vo = CategoryConvert.INSTANCE.categoryPo2Vo(root);
            String code = root.getCode();
            // 获取当前节点的所有子节点
            List<CategoryPo> children = categoryParentCodeGroup.getOrDefault(code, Collections.emptyList());
            if (CollectionUtils.isNotEmpty(children)) {
                // 递归构建子节点
                vo.setChildren(buildTree(children, categoryParentCodeGroup));
            }
            tree.add(vo);
        }
        return tree;
    }
}

